package com.lsh.oms.core.utils.sign;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public enum MessageDigestEnum {

    MD2("MD2"),

    MD5("MD5"),

    SHA1("SHA1"),

    SHA256("SHA-256"),

    SHA384("SHA-384"),

    SHA512("SHA-512");

    MessageDigestEnum(String algorithm) {
        this.algorithm = algorithm;
    }

    private final String algorithm;

    public String getAlgorithm() {
        return this.algorithm;
    }

    public String toString(final String src) {
        return Hex.toHexString(toBytes(src));
    }

    public String toString(final byte[] src) {
        return Hex.toHexString(toBytes(src));
    }

    public byte[] toBytes(final String src) {
        return toBytes(src.getBytes(Charset.forName("UTF-8")));
    }

    public byte[] toBytes(final byte[] src) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance(this.algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return digest.digest(src);
    }
}
